package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private MinioProperties minioProperties;
    @Autowired
    private MinioClient minioClient;

    /**
     * 上传文件到MinIO服务器
     *
     * @param file 要上传的文件
     * @return 返回上传文件的URL路径
     * @throws ServerException           如果服务器发生错误
     * @throws InsufficientDataException 如果数据不足
     * @throws ErrorResponseException    如果响应错误
     * @throws IOException               如果发生I/O错误
     * @throws NoSuchAlgorithmException  如果没有这样的算法
     * @throws InvalidKeyException       如果密钥无效
     * @throws InvalidResponseException  如果响应无效
     * @throws XmlParserException        如果XML解析错误
     * @throws InternalException         如果发生内部错误
     */
    @Override
    public String uploadFile(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        // 检查存储桶是否存在
        boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
        if (!exists) {
            // 如果存储桶不存在，则创建新的存储桶
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            // 配置存储桶策略，允许公开访问存储桶中的对象
            String config = """
                      {
                                                            "Version": "2012-10-17",
                                                            "Statement": [
                                                                {
                                                                    "Effect": "Allow",
                                                                    "Principal": "*",
                                                                    "Action": "s3:GetObject",
                                                                    "Resource": "arn:aws:s3:::%s/*"
                                                                },
                                                                {
                                                                    "Effect": "Allow",
                                                                    "Principal": "*",
                                                                    "Action": "s3:PutObject",
                                                                    "Resource": "arn:aws:s3:::%s/*"
                                                                }
                                                            ]
                                                        }
                    """.formatted(minioProperties.getBucketName(),minioProperties.getBucketName());
            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(minioProperties.getBucketName()).config(config).build());
        }
        // 生成对象名称，包括日期、UUID和原始文件名，以确保唯一性和组织性
        String objectName = new SimpleDateFormat("yyyyMMdd").format(new Date())
                + "/" + UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
        // 将文件上传到MinIO服务器
        // putObject -> 上传运行内存的文件 ||  uploadObject -> 上传本地已有的文件

        minioClient.putObject(PutObjectArgs.builder()
                .bucket(minioProperties.getBucketName())
                .contentType(file.getContentType())
                .object(objectName)
                .stream(file.getInputStream(), file.getSize(), -1)
                .build());
        // 返回上传文件的URL路径
        return String.join("/", minioProperties.getEndPoint(), minioProperties.getBucketName(), objectName);
    }

}
